const Goods = require("../model/goodsModel");
const { Op } = require("sequelize");
class GoodsService {
  async createGoods(goods) {
    const res = await Goods.create(goods);
    return res.dataValues;
  }
  async updateGoods(id, goods) {
    const res = await Goods.update(goods, { where: { id } });
    return res[0] > 0 ? true : false;
  }
  async removeGoods(id) {
    const res = await Goods.destroy({ where: { id } });
    return res > 0 ? true : false;
  }
  async restoreGoods(id) {
    const res = await Goods.restore({ where: { id } });
    return res > 0 ? true : false;
  }
  async findGoods(pageNum, pageSize) {
    const offset = (pageNum - 1) * pageSize;

    console.log("请求参数:", { pageNum, pageSize, offset }); // 打印请求参数和偏移量

    const { count, rows } = await Goods.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
    });

    // console.log("返回的总数:", count); // 打印总数
    // console.log("返回的行数据:", rows); // 打印获取的行数据

    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }
  async searchGoods(pageNum, pageSize, keyword) {
    const offset = (Number(pageNum) - 1) * Number(pageSize);
    const limit = Number(pageSize); // 确保 pageSize 是数字

    const { count, rows } = await Goods.findAndCountAll({
      where: {
        [Op.or]: [{ goods_name: { [Op.like]: `%${keyword}%` } }],
      },
      offset: offset,
      limit: limit, // 确保 limit 是数字
    });
    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }
}
module.exports = new GoodsService();
